package com.sjk.controller;

import com.sjk.pojo.*;
import com.sjk.service.LoginService;
import com.sjk.utils.JWTUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.List;

/**
 * @author lohhhha
 * 2023/5/17
 */

@RestController
public class LoginController {

    @Resource
    LoginService loginService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result userLogin(@RequestBody UserLoginInfo user_info, HttpServletRequest request) {
        User u = loginService.login(user_info.getUsername(), user_info.getPassword());
        if (u != null) {
            // {username,limit}
            List<String> info = new LinkedList<>();
            info.add(u.getUsername());
            info.add(Integer.toString(u.getAuthority()));
            String jwt = JWTUtils.createToken(info);
            request.getSession().setAttribute("jwt", jwt);
            return Result.ok(new LoginReturnInfo(u, jwt));
        }
        return Result.error("not_login");
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Result userRegister(@RequestBody UserRegisterInfo user_info) {
        User u = user_info.getUser(0);
        if (loginService.register(u)) {
            return Result.ok(null);
        }
        return Result.error("register_error");
    }
}
